package com.cc.controller;

import com.cc.entity.Book;
import com.cc.entity.R;
import com.cc.enums.HttpEnum;
import com.cc.service.BookService;
import com.cc.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
@CrossOrigin //解决跨域
public class BookController {

    @Autowired
    BookService bookService;

    //获取全部书籍  作者/书籍名称
    @GetMapping
    public List<Book> getLists(String bookName, String author) {

        return bookService.getList(bookName, author);
    }

    @GetMapping("/page")
    public R<PageInfo<Book>> getPage(String bookName, String author, Integer pageNum) {
        PageInfo<Book> pageBooks = bookService.getPage(bookName, author, pageNum);
        return R.success(pageBooks);
    }

    //获取书籍详情
    @GetMapping("{id}")
    public R<Book> getBookInfo(@PathVariable("id") Integer id) {

        return R.success(bookService.getBookInfo(id));
    }

    //新增书籍
    @PostMapping
    public R saveBook(@Valid Book book, MultipartFile bookImageFile, HttpServletRequest request) {
        //todo 默认设置数据类型为1
        book.setCategoryId(1);
        //得到上传图片的地址
        String imgPath;

        try {
            //ImageUtil为之前添加的工具类
            imgPath = FileUtil.upload(request,bookImageFile);
            if(imgPath != null){
                book.setPathUrl(imgPath);
                System.out.println("---------图片上传成功!");
            }else {
                System.out.println("---------图片上传失败!");
            }
        } catch (IOException e) {
           e.printStackTrace();
            System.out.println("---------图片上传失败!");
        }
        int count = bookService.saveBook(book);

        return count > 0 ? R.success("新增成功") : R.fail(HttpEnum.ERROR.getCode(), "新增失败");
    }

    //修改书籍
    @PutMapping
    public String updateBook(@RequestBody Book book) {
        int count = bookService.updateBook(book);
        if (count > 0) {
            return "修改成功";
        }
        return "修改失败";
    }

    //删除书籍
    @DeleteMapping("{id}")
    public String deleteBook(@PathVariable Integer id) {
        int count = bookService.deleteBook(id);
        if (count > 0) {
            return "删除成功";
        }
        return "删除失败";
    }

}
